<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-toggle-button/paper-toggle-button.html">
<link rel="import" href="../../bower_components/paper-checkbox/paper-checkbox.html">

<link rel="import" href="../app-icons/app-icons.html">
<link rel="import" href="../app-form/app-form.html">

<dom-module id="script-run">
    <template>
        <style include="shared-styles forms single-page">
        p {
            padding: 0 !important;
        }
        #content {
            max-width: 900px;
        }
        paper-material {
            display: block;
            padding: 24px;
        }

        paper-progress {
            position: absolute;
            bottom: 85px;
            width: 100%;
            left: 0;
            right: 0;
        }

        :host >::slotted(paper-input-container) {
            padding-top: 16px;
            padding-bottom: 16px;
        }

        .error {
            color: var(--red-color);
        }
        .error iron-icon {
            color: inherit;
        }
        </style>

        <div id="content">
            <paper-material class="single-head layout horizontal" style$="background-color: [[section.color]]">
                <span class="icon"><iron-icon icon="[[section.icon]]"></iron-icon></span>
                <div class="title flex">
                    <h2>
                        Run [[script.name]]
                    </h2>
                    <div class="subtitle">
                        Run scripts on one machine per time. Create schedules for batch tasks.
                    </div>
                </div>
            </paper-material>
            <paper-material>
                <p>
                    Heads up! Make sure you select a machine you have already associated a key with. Otherwise the the request may be accepted but the script will never finish run.
                </p>
                <p class="error" hidden$="{{machineHasKeys}}">
                    <iron-icon icon="icons:warning"></iron-icon> Machine [[machine.name]] has no associated keys.
                </p>
                <app-form fields="[[fields]]" url="/api/v1/scripts/[[script.id]]" on-response="_runScriptResponse" btncontent="run"></app-form>
            </paper-material>
        </div>
    </template>

    <script>
        (function() {
            'use strict';

            Polymer({
                is: 'script-run',

                properties: {
                    model: {
                        type: Object
                    },
                    script: {
                        type: Object,
                    },
                    section: {
                        type: Object
                    },
                    fields: {
                        type: Array,
                    },
                    parameters: {
                        type: String,
                        value: null
                    },
                    machinesOptions: {
                        type: Array,
                        value: []
                    },
                    hasMachines: {
                        type: Boolean,
                        computed: '_computeHasMachines(machinesOptions.*)'
                    },
                    cardTitleText: {
                        type: String,
                        computed: '_computeCardTitleText(script.name, runScript.machine)'
                    },
                    machine: {
                        type: Object
                    },
                    machineHasKeys: {
                        type: Boolean,
                        value: true,
                        computed: '_machineChanged(machine)'
                    }
                },
                observers: [
                    '_cloudsChanged(fields.length, model.cloudsArray.*, model.machines.*, model.keysArray.*)'
                ],
                listeners: {
                    'iron-select': '_fieldsChanged'
                },
                ready: function(){
                    var arr = this.machinesOptions || [];
                    var fields = [{
                            name: "machine_uuid",
                            label: "Select Machine *",
                            type: "mist_dropdown",
                            value: "",
                            defaultValue: "",
                            placeholder: "",
                            helptext: "Choose the machine on which the script will run",
                            show: true,
                            required: true,
                            options: arr
                        }, {
                            name: "cloud_id",
                            label: "Cloud ID",
                            type: "text",
                            value: "",
                            defaultValue: "",
                            placeholder: "",
                            helptext: "The cloud ID of the machine.",
                            show: false,
                            showIf: {
                                fieldName: "machine_id",
                                fieldExists: true
                            },
                            required: true,
                            disabled: true
                        }, {
                            name: "params",
                            label: "Parameters",
                            type: "textarea",
                            value: "",
                            defaultValue: "",
                            placeholder: "",
                            helptext: "Optional. Fill in the scripts pareameters.",
                            errorMessage: "Please enter network's name",
                            show: true,
                            required: false
                         }];
                    this.set('fields', fields);
                },
                _computeMachinesOptions: function(clouds) {
                    return Object.values(this.model.machines).filter(function(cloud) {
                            return cloud.enabled;
                        });
                },
                _computeHasMachines: function(machinesOptions) {
                    return machinesOptions.base.length > 0;
                },
                _computeFieldType: function(field, value, show) {
                    if (!(field.showIf && !field.show)) {
                        return field.type == value;
                    }
                },
                _computeCardTitleText: function(name, machine) {
                    return machine ? 'Run Script "' + name + '" on "' + machine.name + '"' : 'Run Script "' + name + '"';
                },
                _fieldsChanged: function() {
                    var machine = this.fields.find(function(f){
                        return f.name.startsWith("machine");
                    });
                    var cloud = this.fields.find(function(f, index){
                        return f.name.startsWith("cloud");
                    });
                    if (machine && machine.value) {
                        var machineId = machine.value;
                        this.set("machine", this.model.machines[machineId]);
                        this.set('fields.1.value', this.model.machines[machineId].cloud);
                    };

                },
                _machineChanged: function(machine){
                    return machine.key_associations && machine.key_associations.length > 0 ? true : false;
                },
                _cloudsChanged: function(fieldsLength, clouds, machines, keys) {

                    this.set('fields.0.options', Object.values(this.model.machines));

                    if (this.fields && this.fields[0] && this.fields[0].options) {
                        this.fields[0].options.forEach(function (o, index){
                            if (o && o.key_associations && o.key_associations.length > 0){
                                this.set('fields.0.options.'+index+'.icon', 'communication:vpn-key');
                            } else {
                                this.set('fields.0.options.'+index+'.icon', 'nokey');
                            }
                        }, this);
                    }
                },
                _runScriptResponse: function(e) {
                    this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {msg:'Run script request was successfull. Redirecting to script...',duration:3000} }));

                    this.async(function(){
                        this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail: {url: '/scripts/'+this.script.id} }));
                    }, 3300)
                },
            });
        })();
    </script>
</dom-module>
